<?php

App::uses('Controller', 'Controller');

/**
 * Application Controller
 *
 * Add your application-wide methods in the class below, your controllers
 * will inherit them.
 *
 * @package       app.Controller
 * @link http://book.cakephp.org/2.0/en/controllers.html#the-app-controller
 */
class AppController extends Controller {

    public $helpers = array('Html', 'Session', 'Cache');
    public $components = array(
        'RequestHandler',
        'Session',
        'Auth' => array(
            'authorize' => 'Controller',
            'loginAction' => array(
                'controller' => 'users',
                'action' => 'login',
                'admin' => false
            ),
        ),
        'Static'
    );

    public function beforeFilter() {
//        $this->request->addDetector('json', array('callback' => function($request) {
//                return $request->params['ext'] == "json";
//            }));
        
        $this->checkClearCache();
        
        if (isset($_GET['debug'])) {
            Configure::write('debug', 2);
        }
        
        
        if (isset($this->request->params['page'])) {
            $this->request->params['named']['page'] = $this->request->params['page'];
        }


        $this->Auth->allow();

        if (!empty($this->request->params['admin']) && $this->request->params['admin']) {
            $this->layout = 'admin';
        }
        if (isset($this->request->query['clearcache'])) {
            Cache::clear();
        }
    }
    
    public function afterFilter() {
        return;
        $nocacheHeader = $this->request->header('No-cache');
        if($nocacheHeader !== false) return;
        if($this->request->isPost() || $this->request->isPut()){
            return;
        }
        if (!empty($this->cacheAction) && empty($this->request->params['admin'])) {
            $this->log('Cache static for ' . $this->here, 'debug');
            $this->Static->create($this->response->body());
        }
    }
    
    
    /**
     * Check if there is clearcache parameter in GET and clear all app cache.
     * After it clears cache it will reload the page. 
     */
    private function checkClearCache(){
        
        if ($this->here == '/clearcache') {
            Cache::clear();
            $this->Static->clear();
            clearCache(null, 'views');
            clearCache(null, 'models');
            clearCache(null, 'persistent');
            $this->redirect('/');
            die();
        }
    }

    public function isAuthorized($user = null) {

        // Any registered user can access public functions
        if (empty($this->request->params['admin'])) {
            return true;
        }
        // Only admins can access admin functions
        if (isset($this->request->params['admin'])) {

            return (bool) ($user['admin'] === true);
        }

        // Default alow
        return true;
    }

    protected function createSlug($modelName, $name, $replacement = '-') {
        $this->loadModel($modelName);
        /**
         * Slug counter.
         * If generated slug exists increment value and insert at end of string and check again.
         */
        $no = 0;
        /**
         * Base slug. At end add counter (if != 0)
         */
        $slugBase = str_replace("_", $replacement, strtolower(Inflector::slug($name, $replacement)));
        /**
         * Slug to return.
         * It can't be null.
         */
        $slug = null;
        while (true) {
            $slug = $slugBase;
            if ($no != 0) {
                $slug .= '-' . $no;
            }
            $cnt = $this->{$modelName}->find('count', array(
                'conditions' => array($modelName . '.slug' => $slug)
                    ));

            if ($cnt > 0) {
                $no++;
                continue;
            }

            break;
        }
        return $slug;
    }

}
